package cn.lopr.im.android.mvp.model;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Map;

import cn.lopr.im.android.bean.CallbackResult;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.Constant;
import cn.lopr.im.android.common.OnCallBackListener;
import cn.lopr.im.android.mvp.contact.ILoginContact;
import cn.lopr.im.android.utils.Apis;
import cn.lopr.im.android.utils.HttpUtils;

/**
 * model 用于和 数据 打交道
 *
 * @author shuangyang7
 * @date 2020/12/19 11:51
 */
public class LoginModel implements ILoginContact.ILoginModel {

    @Override
    public void login(String phone, String password, OnCallBackListener<CallbackResult<Map<String, Object>>, String> onCallBackListener) {

        String param = String.format("?phone=%s&password=%s", phone, password);
        // ip:port/url param
        // http://  localhost  : 8080  /im/user/login?phone=18255431881&password=000
        HttpUtils.doGetForResult(Apis.WebApis.LOGIN.getValue(), param, data -> {

            Log.d("json", data);

            if (TextUtils.isEmpty(data)) {
                onCallBackListener.failure(Constant.CALLBACK_ERROR_MESSAGE);
                return;
            }

            Type jsonType = new TypeToken<CallbackResult<Map<String, Object>>>() {
            }.getType();
            CallbackResult<Map<String, Object>> callbackResult = new Gson().fromJson(data, jsonType);

            if (callbackResult.getStatus() == Constant.ResponseCode.SUCCESS.getCode()) {
                onCallBackListener.success(callbackResult);

            } else {
                onCallBackListener.failure(callbackResult.getMsg());

            }
        });

    }

    @Override
    public void isLogin(String token, OnCallBackListener<CallbackResult<User>, String> onCallBackListener) {
        HttpUtils.doGetForResult(Apis.WebApis.IS_LOGIN.getValue(), "", token, data -> {

            Type jsonType = new TypeToken<CallbackResult<User>>() {
            }.getType();
            CallbackResult<User> callbackResult = new Gson().fromJson(data, jsonType);

            if (callbackResult.getStatus() == Constant.ResponseCode.SUCCESS.getCode()) {
                onCallBackListener.success(callbackResult);

            } else {
                onCallBackListener.failure(callbackResult.getMsg());

            }
        });
    }
}
